import TagGroup from '@/components/TagGroup';
import { treeOrganization } from '@/services/api/api-admin-organization';
import { getRolePage } from '@/services/api/api-admin-role';
import {
  ActionType,
  ProFormCascader,
  ProFormDigit,
  ProFormRadio,
} from '@ant-design/pro-components';
import { DrawerForm, ProFormInstance } from '@ant-design/pro-form';
import ProTable from '@ant-design/pro-table';
import { Form, message } from 'antd';
import { DefaultOptionType } from 'antd/es/select';
import { DataNode } from 'antd/es/tree';
import React, { useRef, useState } from 'react';

interface EditAccountOrganizationProps {
  id: string;
  organizationCascaderIds: string[];
  roles: AdminAccountBo.AccountOrganizationRolesBo[];
  marks: string[];
  onRefurbish: (value: AdminAccountBo.AccountOrganizationSaveBo) => boolean;
  seq: number;
  state: number;
}
const EditAccountOrganization: React.FC<EditAccountOrganizationProps> = ({
  organizationCascaderIds,
  roles,
  marks,
  onRefurbish,
  seq,
  state,
}) => {
  const formRef = useRef<ProFormInstance>();

  const userRef = useRef<ActionType>();

  const [selectedRoleRows, setSelectedRoleRowsState] = useState<
    AdminAccountBo.AccountOrganizationRolesBo[]
  >([]);

  /**
   * 初始化树形数据
   */
  const [treeOrganizationData, setTreeOrganizationDataState] = useState<DataNode[]>();

  /**
   * 预备Tree结构数据
   * @param data
   */
  function readyTreeData(data: AdminOrganizationData.Organization[]): any {
    const treeData = new Array();
    if (data) {
      data.forEach((val) => {
        treeData.push({
          label: val.name,
          value: val.id,
          disabled: val.isFolder === 1 && val.isOrganization === 0 && val.children === undefined,
          children: readyTreeData(val.children as AdminOrganizationData.Organization[]),
        });
      });
    }
    return treeData;
  }

  /**
   * 预备Tree结构数据
   * @param data
   */
  function extractOrganizations(organizationId: string): any {
    let result = null;

    let fn = function (list: any[]) {
      if (Array.isArray(list)) {
        // 判断是否是数组
        for (let i = 0; i < list.length; i++) {
          const element = list[i];
          if (element.value === organizationId) {
            // 数据循环每个子项，并且判断子项下边是否有id值
            // 返回的结果等于每一项
            result = {
              organizationId: element.value,
              organizationName: element.label,
            };
            break;
          } else if (element.children) {
            fn(element.children); // 递归调用下边的子项
          }
        }
      }
    };

    fn(treeOrganizationData!);
    return result;
  }

  /**
   * 加载组织详情
   * @param key
   */
  const loadOrganizationData = async () => {
    try {
      const response = await treeOrganization();
      if (response.code === 0) {
        const treeData = readyTreeData(response.data);
        setTreeOrganizationDataState(treeData);
      }
    } catch (error) {}
  };

  const filter = (inputValue: string, path: DefaultOptionType[]) =>
    path.some(
      (option) => (option.label as string).toLowerCase().indexOf(inputValue.toLowerCase()) > -1,
    );

  return (
    <DrawerForm
      key="edit_account_organization_drawer"
      title="添加组织"
      drawerProps={{
        destroyOnClose: true,
      }}
      trigger={<a key="edit_a">编辑</a>}
      formRef={formRef}
      initialValues={{
        organizationIds: organizationCascaderIds,
        marks: marks,
        seq: seq,
        state: state,
      }}
      onOpenChange={(visible: boolean) => {
        if (visible) {
          loadOrganizationData();
          setSelectedRoleRowsState(roles);
        } else {
          setSelectedRoleRowsState([]);
        }
      }}
      onFinish={async (values) => {
        const organizations = new Array();

        values.organizationIds.forEach((item: string) => {
          organizations.push(extractOrganizations(item));
        });

        if (organizations.length === 0) {
          message.warning('请选择组织');
          return false;
        }

        if (selectedRoleRows.length === 0) {
          message.warning('请选择角色');
          return false;
        }

        return onRefurbish({
          organizations,
          organizationCascaderIds: values.organizationIds,
          roles: selectedRoleRows,
          marks: values.marks,
          seq: values.seq,
          state: values.state,
        });
      }}
    >
      <ProFormCascader
        fieldProps={{
          size: 'large',
          options: treeOrganizationData,
          showSearch: { filter },
        }}
        name="organizationIds"
        placeholder="选择组织"
        disabled
        rules={[
          {
            required: true,
            message: '选择组织!',
          },
        ]}
      />
      <ProFormDigit width="md" label="排序" name="seq" min={0} max={1000} />
      <ProFormRadio.Group
        name="state"
        label="状态"
        options={[
          {
            label: '启用',
            value: 1,
          },
          {
            label: '禁用',
            value: 0,
          },
        ]}
      />
      <Form.Item
        label={<>标记</>}
        name="marks"
        // extra={
        //   <div
        //     style={{
        //       marginLeft: '28px',
        //     }}
        //   >
        //     最少输入一个
        //   </div>
        // }
      >
        <TagGroup
          style={{
            marginLeft: '28px',
          }}
        />
      </Form.Item>
      <ProTable<AdminRoleData.Role>
        ghost
        rowSelection={{
          selectedRowKeys: selectedRoleRows.map((item) => item.roleId),
          type: 'checkbox',
          onChange: (selectedRowKeys: React.Key[], selectedRows: any) => {
            setSelectedRoleRowsState(
              selectedRows.map((item: AdminRoleData.Role) => {
                return {
                  roleId: item.id,
                  roleName: item.name,
                };
              }),
            );
          },
        }}
        tableAlertRender={false}
        columns={[
          {
            title: '名称',
            key: 'name',
            dataIndex: 'name',
          },
          {
            title: '描述',
            key: 'describes',
            dataIndex: 'describes',
          },
        ]}
        request={async (params = {}) => {
          params.state = 1;
          params.deleted = 0;
          const response = await getRolePage({
            ...params,
          });
          return Promise.resolve({
            data: response.data.data,
            total: response.data.total,
            success: response.code === 0,
          });
        }}
        rowKey="id"
        options={false}
        search={false}
        tableLayout="fixed"
        dateFormatter="string"
        headerTitle="角色列表"
        bordered
        pagination={{
          showQuickJumper: true,
          showSizeChanger: true,
          defaultPageSize: 50,
        }}
      />
    </DrawerForm>
  );
};
export default EditAccountOrganization;
